package com.example.networkdemo2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void httpPost(View view) throws MalformedURLException {
        // 创建线程处理网络访问 new Thread( new Runnable...).start()
        URL url = new URL("http://10.1.91.101:8090/app1/user/login");
        final String data = "{\"name\":\"张三\",\"password\":\"123\"} ";
        postdata(url, data);


    }

    private void postdata(final URL url, final String data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    // 准备数据

                    // 提交数据
                    conn.setRequestProperty("Content-Type", "application/json");
                    byte[] datab = data.getBytes();
                    conn.setRequestProperty("Content-Length", datab.length + "");
                    conn.setDoOutput(true);
                    OutputStream outputStream = conn.getOutputStream();
                    outputStream.write(datab);
                    outputStream.flush();
                    // 接收数据
                    InputStream is = conn.getInputStream();
                    byte[] b = new byte[1024]; // 创建字节数组，以保存返回字节
                    int len = is.read(b); // 读取数据 len读取的字节数
                    String s = new String(b, 0, len);
                    // 取出json对象中success属性的值
                    JSONObject jsonObject = new JSONObject(s); // json对象字符串，解析为 Java中的对象（JSONObject类型）
                    boolean success = jsonObject.getBoolean("success");
                    final String msg = jsonObject.getString("msg");
                    if (success) {
                        // 显示成功
                        // 不能在子线程中操作UI 。比如运行在UI主线程
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        // 显示失败
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    Log.e("TAG", "run: " + s); // new String（b）构建字符串
                    // 关闭连接
                    conn.disconnect();

                    /*// url
                    // 注意： ip地址应为服务端所运行的机器IP
                    URL url = new URL("http://10.1.91.101:8090/app3/classmate/list");
                    // conn HttpURLConnection
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    // header
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    // 接收数据
                    InputStream is = conn.getInputStream();
                    byte[] b = new byte[1024]; // 创建字节数组，以保存返回字节
                    int len = is.read(b); // 读取数据 len读取的字节数
                    Log.e("TAG", "run: "+new String(b,0,len) ); // new String（b）构建字符串
                    // 关闭连接
                    conn.disconnect();

                     */

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}